package com.ivanceras.client.widgets;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.ivanceras.shared.bo.Ad_column;
import com.ivanceras.shared.bo.Ad_field;
import com.ivanceras.shared.bo.Ad_tab;
import com.ivanceras.shared.db.DAO;

public class SingleRecordUi extends Composite {

	private static SingleRecordUiUiBinder uiBinder = GWT
			.create(SingleRecordUiUiBinder.class);

	interface SingleRecordUiUiBinder extends UiBinder<Widget, SingleRecordUi> {
	}

	@UiField HTML daoValue;
	String[] identifierColumns = null;
	
	public SingleRecordUi(Ad_tab tab, final ClickHandler listener) {
		initWidget(uiBinder.createAndBindUi(this));
		identifierColumns = getIdentifierColumns(tab);
		daoValue.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				listener.onClick(event);
			}
			
		});
	}
	
	public void setDao(DAO dao){
		StringBuffer value = new StringBuffer();
//		boolean doUscore = false;
//		for(String col : identifierColumns){
//			if(doUscore){
//				value.append("_");
//			}
//			value.append(dao.get_Value(col).toString());
//			doUscore = true;
//		}
		value.append(dao.get_Value("name"));
 		daoValue.setHTML(value.toString());
	}

	private String[] getIdentifierColumns(Ad_tab tab){
		Ad_field[] fieldList = tab.getAd_fieldList();
		List<String> identifiers = new ArrayList<String>();
		for(Ad_field field : fieldList){
			Ad_column column = field.getAd_column();
			if(column != null && column.getIsidentifier() != null && column.getIsidentifier().equals("Y")){
				identifiers.add(column.getColumnname().toLowerCase());
			}
		}
		return identifiers.toArray(new String[identifiers.size()]);
	}

	public void setSelected(boolean isSelected) {
		if(isSelected){
			daoValue.addStyleName("selected");
		}else{
			daoValue.removeStyleName("selected");
		}
	}

	public void clear() {
		daoValue.setHTML("");
		daoValue.removeStyleName("selected");
	}
}
